package info.batcloud.fanli.core.service.impl;

import info.batcloud.fanli.core.entity.Crowd;
import info.batcloud.fanli.core.entity.User;
import info.batcloud.fanli.core.enums.CrowdStatus;
import info.batcloud.fanli.core.repository.CrowdRepository;
import info.batcloud.fanli.core.repository.UserRepository;
import info.batcloud.fanli.core.service.CrowdService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

@Service
public class CrowdServiceImpl implements CrowdService {

    @Inject
    private CrowdRepository crowdRepository;

    @Inject
    private UserRepository userRepository;

    @Override
    public void createCrowd(CrowdCreateParam param) {
        Crowd crowd = new Crowd();
        BeanUtils.copyProperties(param, crowd);
        crowdRepository.save(crowd);
    }

    @Override
    public void updateCrowd(long id, CrowdUpdateParam param) {
        Crowd crowd = crowdRepository.findOne(id);
        BeanUtils.copyProperties(param, crowd);
        crowdRepository.save(crowd);
    }

    @Override
    public boolean checkUser(User user, Crowd crowd) {
        if (crowd.getUserLevel() != null && user.getLevel().level != crowd.getUserLevel().level) {
            return false;
        }
        if (crowd.getMinCreateTime() != null && user.getCreateTime().before(crowd.getMinCreateTime())) {
            return false;
        }
        if (crowd.getMaxCreateTime() != null && user.getCreateTime().after(crowd.getMaxCreateTime())) {
            return false;
        }
        if (crowd.getMinActiveTime() != null && crowd.getMinActiveTime().after(user.getLastActiveTime())) {
            return false;
        }
        if (crowd.getMaxActiveTime() != null && crowd.getMaxActiveTime().before(user.getLastActiveTime())) {
            return false;
        }
        return true;
    }

    @Override
    public boolean checkUser(long userId, long crowdId) {
        return checkUser(userRepository.findOne(userId), crowdRepository.findOne(crowdId));
    }

    @Override
    public List<Crowd> listAll() {
        return crowdRepository.findByStatusNotOrderByIdDesc(CrowdStatus.DELETED);
    }

    @Override
    public List<Crowd> listAll(CrowdStatus status) {
        return crowdRepository.findByStatusOrderByIdDesc(status);
    }

    @Override
    public void setStatus(long id, CrowdStatus status) {
        Crowd crowd = crowdRepository.findOne(id);
        crowd.setStatus(status);
        crowdRepository.save(crowd);
    }
}
